package org.ssssssss.magicapi.servlet.jakarta;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.jfr.DataAmount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.utils.IpUtils;

import java.io.PrintWriter;


/**
 * Web 接口管理界面 IP白名单
 */
public class WebIPLimitRequestInterceptor implements MagicWebInterceptor {

    public final static String START_PLUGIN_LOG_MSG="已开启[{}],如需关闭[{}],插件配置信息:[{}]";
    private static final Logger log = LoggerFactory.getLogger(WebIPLimitRequestInterceptor.class);
    /**
     * 白名单
     */
    private String whitelist;

    private String blacklist;

    @PostConstruct
    public void initIpLimitRequestInterceptor() {
        log.info(START_PLUGIN_LOG_MSG, "Web UI IP白名单", "magic-api.web-iplimit.enable=false", "magic-api.web-iplimit.whitelist=ip地址逗号分隔");
    }


    private boolean isIpInBlacklist(String ip) {
        return  blacklist!=null&&!blacklist.isEmpty() && blacklist.contains(ip);
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IpUtils.getRealIP(request.getRemoteAddr(), request::getHeader, null);
        if (ip == null) {
            return true;
        }
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            return true;
        }
        boolean isAllow = !isIpInBlacklist(ip);
        if (whitelist != null && !whitelist.isEmpty() && !whitelist.contains(ip)) {
            isAllow=false;
        }
        if (!isAllow ) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(String.format("当前IP:[%s]无权访问该资源,请联系管理员！", ip));
            writer.flush();
            return false;
        }else{
            return true;
        }
    }

    public String getWhitelist() {
        return whitelist;
    }

    public void setWhitelist(String whitelist) {
        this.whitelist = whitelist;
    }

    public String getBlacklist() {
        return blacklist;
    }

    public void setBlacklist(String blacklist) {
        this.blacklist = blacklist;
    }
}
